package com.whosly.spring.cloud.example.apollo.config.data;


import com.whosly.spring.cloud.example.apollo.config.ApplicationContextAwareHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * 配置信息的变更， dynamic
 */
public interface IDynamicData {
    Logger LOGGER = LoggerFactory.getLogger(IDynamicData.class);

    /**
     * 更新SpringApplicationContext对象，并更新
     *
     * @param properPrefix   监听的配置前缀。 如 "jwt."
     * @param changedKeys
     * @param target
     * @return
     */
    default boolean refresh(String properPrefix, Set<String> changedKeys, String target){
        boolean propertiesChanged = false;

        for (String changedKey : changedKeys) {
            //前缀为 jwt 的key发生了改变
            if (changedKey.startsWith(properPrefix)) {
                propertiesChanged = true;
                break;
            }
        }

        //更新配置
        if (propertiesChanged) {
            refresh(changedKeys, target);
        }

        return true;
    }

    /**
     * 更新SpringApplicationContext对象，并更新
     *
     * @param changedKeys
     * @param target
     * @return
     */
    default boolean refresh(Set<String> changedKeys, String target){
        if(!CollectionUtils.isEmpty(changedKeys)){
            LOGGER.info("Refreshing IDynamicData:{} properties:{}!", target, changedKeys);

            //更新配置
            ApplicationContextAwareHolder.getContext()
                    .publishEvent(new EnvironmentChangeEvent(changedKeys));

            LOGGER.info("properties refreshed!");
        }


        return true;
    }
}